﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using CustomPublishButton = SlamCms.SharePoint.Publishing.CustomActions.PublishButton;
using CustomSubmitForApprovalButton = SlamCms.SharePoint.Publishing.CustomActions.SubmitForApprovalButton;
//using CustomDeleteButton = Slam.Cms.SharePoint.Publishing.CustomActions.DeleteButton;
using Microsoft.SharePoint;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using SlamCms.Common.Security;
using SlamCms.SharePoint.Publishing.Services;

namespace SlamCms.SharePoint.Publishing.CustomActions
{
	public class PublishingControlLoader : WebControl
	{
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New)
			{
				SPRibbon currentRibbon = SPRibbon.GetCurrent(this.Page);
				SPList list = SPContext.Current != null ? SPContext.Current.List : null;

				if (list == null)
				{
					SPWeb site = SPControl.GetContextWeb(HttpContext.Current);
					list = site.GetListFromUrl(HttpContext.Current.Request.RawUrl);
				}

				if (!list.EnableModeration)
				{
					if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)
					{
						currentRibbon.TrimById("EditFormPublishingPublishButtonDocLib");
						currentRibbon.TrimById("EditFormPublishingSaveDraftButtonDocLib");
						currentRibbon.TrimById("EditFormPublishingSubmitApprovalButtonDocLib");
						if (SPContext.Current.FormContext.FormMode == SPControlMode.New)
						{
							currentRibbon.TrimById("NewFormPublishingPublishButtonDocLib");
							currentRibbon.TrimById("NewFormPublishingSaveDraftButtonDocLib");
							currentRibbon.TrimById("NewFormPublishingSubmitApprovalButtonDocLib");
						}
					}
					else if (list.BaseTemplate == SPListTemplateType.Events)
					{
						currentRibbon.TrimById("EditFormPublishingPublishButtonCalendar");
						currentRibbon.TrimById("EditFormPublishingSaveDraftButtonCalendar");
						currentRibbon.TrimById("EditFormPublishingSubmitApprovalButtonCalendar");
						if (SPContext.Current.FormContext.FormMode == SPControlMode.New)
						{
							currentRibbon.TrimById("NewFormPublishingPublishButtonCalendar");
							currentRibbon.TrimById("NewFormPublishingSaveDraftButtonCalendar");
							currentRibbon.TrimById("NewFormPublishingSubmitApprovalButtonCalendar");
						}
					}
					else
					{
						currentRibbon.TrimById("EditFormPublishingPublishButton");
						currentRibbon.TrimById("EditFormPublishingSaveDraftButton");
						currentRibbon.TrimById("EditFormPublishingSubmitApprovalButton");
						if (SPContext.Current.FormContext.FormMode == SPControlMode.New)
						{
							currentRibbon.TrimById("NewFormPublishingPublishButton");
							currentRibbon.TrimById("NewFormPublishingSaveDraftButton");
							currentRibbon.TrimById("NewFormPublishingSubmitApprovalButton");
						}
					}
				}
				else
				{
					currentRibbon.TrimById("Ribbon.ListForm.Edit.Commit.Publish");
					currentRibbon.TrimById("Ribbon.DocLibListForm.Edit.Commit.Publish");

					SPSite siteCollection = SPControl.GetContextSite(HttpContext.Current);
					Guid approvalFeatureId = new Guid("dbddef47-c40c-44a8-b0f0-3a5fdf15608f");
					bool approvalEnabled = siteCollection.Features.Any(f => f.DefinitionId.Equals(approvalFeatureId));

					if (!approvalEnabled)
					{
						currentRibbon.TrimById("EditFormPublishingSubmitApprovalButton");
						currentRibbon.TrimById("EditFormPublishingSubmitApprovalButtonDocLib");
						currentRibbon.TrimById("EditFormPublishingSubmitApprovalButtonCalendar");
						if (SPContext.Current.FormContext.FormMode == SPControlMode.New)
						{
							currentRibbon.TrimById("NewFormPublishingSubmitApprovalButton");
							currentRibbon.TrimById("NewFormPublishingSubmitApprovalButtonDocLib");
							currentRibbon.TrimById("NewFormPublishingSubmitApprovalButtonCalendar");
						}
					}
				}

				ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Core.js", false, true);
				ScriptLink.RegisterScriptAfterUI(this.Page, "CUI.js", false, true);
				ScriptLink.RegisterScriptAfterUI(this.Page, "core.js", true, false);
				ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Ribbon.js", false, true);
				ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Runtime.js", false, true);
				ScriptLink.RegisterScriptAfterUI(this.Page, "SP.js", false, true);
				ScriptLink.RegisterScriptAfterUI(this.Page, "SlamCms.PublishingPageComponent.js", false, true);
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			bool isGlobalSettingsSite = SPContext.Current.Web.Name.Equals("GlobalSettings", StringComparison.OrdinalIgnoreCase);
			if (SPContext.Current.Web.ParserEnabled != SPContext.Current.Web.IsRootWeb || SPContext.Current.Web.ParserEnabled != isGlobalSettingsSite)
			{
				SPSecurity.RunWithElevatedPrivileges(delegate()
				{
					using (SPSite elevatedSite = new SPSite(SPContext.Current.Web.Site.ID))
					{
						using (SPWeb elevatedWeb = elevatedSite.AllWebs[SPContext.Current.Web.ID])
						{	
							elevatedWeb.AllowUnsafeUpdates = true;
							elevatedWeb.ParserEnabled = SPContext.Current.Web.IsRootWeb || isGlobalSettingsSite;
							elevatedWeb.Update();
							elevatedWeb.AllowUnsafeUpdates = false;
						}
					}
				});
			}
			
			SPUser currentUser = SPContext.Current.Web.CurrentUser;
			if (currentUser != null && currentUser.LoginName != null)
			{
				string currentUserName = currentUser.LoginName.Contains('|') ? currentUser.LoginName.Substring(currentUser.LoginName.LastIndexOf('|') + 1) : currentUser.LoginName;
				string currentLoginName = currentUser.LoginName;

				if (String.IsNullOrEmpty(currentUser.Name) || currentUser.Name.Equals(currentUserName, StringComparison.OrdinalIgnoreCase))
				{
					Guid userGuid = Guid.Empty;
					try
					{
						userGuid = new Guid(currentUserName);
					}
					catch { }

					if (userGuid != Guid.Empty)
					{
						SPSecurity.RunWithElevatedPrivileges(delegate()
						{
							using (SPSite elevatedSite = new SPSite(SPContext.Current.Web.Site.ID))
							{
								using (SPWeb elevatedWeb = elevatedSite.AllWebs[SPContext.Current.Web.ID])
								{
									elevatedWeb.AllowUnsafeUpdates = true;
									SPUser userToUpdate = elevatedWeb.AllUsers[currentLoginName];
									UserService userService = new UserService();
									userToUpdate.Name = userService.GetUserName(currentUserName);
									userToUpdate.Update();
									elevatedWeb.AllowUnsafeUpdates = false;
								}
							}
						});

						Page.Response.Redirect(Page.Request.Url.ToString());
					}
				}
			}

			if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New)
			{
				SPRibbon currentRibbon = SPRibbon.GetCurrent(this.Page);
				SPList list = SPContext.Current != null ? SPContext.Current.List : null;

				if (list == null)
				{
					SPWeb site = SPControl.GetContextWeb(HttpContext.Current);
					list = site.GetListFromUrl(HttpContext.Current.Request.RawUrl);
				}

				if (currentRibbon != null && list.EnableModeration)
				{
					CustomPublishButton publishButton = new CustomPublishButton();
					publishButton.ID = "publishAndSaveButton";
					this.Page.Form.Controls.Add(publishButton);

					CustomSubmitForApprovalButton submitForApprovalButton = new CustomSubmitForApprovalButton();
					submitForApprovalButton.ID = "submitForApprovalButton";
					this.Page.Form.Controls.Add(submitForApprovalButton);
					
					this.Page.Form.Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"slamCmsPublishingPublishButtonId\" value=\"" + publishButton.ClientID + "_ctl00_diidIOSaveItem\" />"));
					this.Page.Form.Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"slamCmsPublishingSubmitForApprovalButtonId\" value=\"" + submitForApprovalButton.ClientID + "_ctl00_diidIOSaveItem\" />"));
				}
			}
			base.OnLoad(e);
		}
	}
}
